package dashboard.json;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonUtils {
	private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
	 
    public static String bean2Json(Object obj) {
//    	JsonObject jsonObject =
        return gson.toJson(obj);
    }
 
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return gson.fromJson(jsonStr, objClass);
    }
    
    public static <T> T fromJSON(String jsonStr,Type t) {
    	return gson.fromJson(jsonStr, t);
    }
 
    public static String jsonFormatter(String uglyJsonStr) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(uglyJsonStr);
        String prettyJsonString = gson.toJson(je);
        return prettyJsonString;
    }
    
    @SuppressWarnings("unchecked")
	public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
//        String jsonStr = "{'city_name':0,'cost':1,'cost_chain':2,'pv':1,'pv_chain':2,'adpv':1,'adpv_chain':2,'pvr':2,'pvr_chain':2,'disp':1,'disp_chain':2, 'click':1,'click_chain':2,'asn':1,'asn_chain':2,'acp':1,'acp_chain':2,'ctr2':2,'ctr2_chain':2}";
        String numbersJson = gson.toJson(numbers);
        String daysJson = gson.toJson(days);
        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);
        
		List<People> friends = new ArrayList<People>();
		friends.add(JsonJacksonUtils.createAPeople("小明", null));
		friends.add(JsonJacksonUtils.createAPeople("Tony", null));
		friends.add(JsonJacksonUtils.createAPeople("陈小二", null));
        People p = JsonJacksonUtils.createAPeople("邵同学", friends);
        System.out.println("daysJson = " + gson.toJson(p));
        Map<Integer, Integer> map =  (Map<Integer, Integer>)gson.fromJson("{\"cate\":'1'}", Map.class);
        System.err.println( map.get("1") );
	}
}
